package org.dromara.tearoom.service.impl;


import lombok.RequiredArgsConstructor;
import org.apache.dubbo.common.utils.JsonUtils;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.tearoom.domain.vo.KuodaoParam;
import org.dromara.tearoom.domain.vo.OpenDoorParam;
import org.dromara.tearoom.util.JSONNUtil;
import org.dromara.tearoom.util.RestLogUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**阔道三方密钥获取**/
@RequiredArgsConstructor
@Service
public class KuodaoService {
    private final RestTemplate restTemplate ;
    @Value("${kuodao.name}")
    private  String name;

    @Value("${kuodao.passwd}")
    private  String passwd;

    public String getKuodaoSessionId() {
        /*会话登录*/
        String loginurl = "https://api.kdware.cn/hapi/v1.1/login";

        // 请求体数据

        KuodaoParam account = new KuodaoParam();
        account.setName(name);
        account.setPasswd(passwd);
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 创建 HttpEntity 对象
        HttpEntity<KuodaoParam> requestloginEntity = new HttpEntity<>(account, headers);

        // 调用 POST 接口
        KuodaoParam loginresponse = restTemplate.postForObject(loginurl, requestloginEntity ,KuodaoParam.class);

        if(loginresponse.getResultCode()!=0)return null;

        return loginresponse.getSessionid();
    }
    public void outLogin(String sessionid) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 会话退出
        String outurl = "https://api.kdware.cn/hapi/v1.1/logout";

        // 请求体数据
        Map<String, String> rsloginoutBody = new HashMap<>();
        rsloginoutBody.put("sessionid", sessionid);

        // 创建 HttpEntity 对象
        HttpEntity<Map<String, String>> requestloginoutEntity = new HttpEntity<>(rsloginoutBody, headers);

        // 调用 POST 接口
        restTemplate.exchange(outurl, HttpMethod.POST, requestloginoutEntity, String.class);
    }

    /**
     * 密钥申请-钥匙 -密码
     */
    public KuodaoParam applyKey(KuodaoParam kparam) {


        kparam.setSessionid(getKuodaoSessionId());
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        String url = "https://api.kdware.cn/hapi/v1.1/issueGuestEKey";
        headers.setContentType(MediaType.APPLICATION_JSON);


        OpenDoorParam apply = new OpenDoorParam();
        apply.setSessionid(kparam.getSessionid());
        apply.setOwner(kparam.getOwner());
        apply.setSysID(kparam.getSysID());
        apply.setRoomID(kparam.getRoomID());
        apply.setUserId(kparam.getUserId());
        apply.setSDKClientId("shangpiguan01_sdk_client");
        apply.setSDKClientSecret("I2pgpBNBYAwmotCInLkLufez2BMClEpg");
        apply.setEndDate(kparam.getEndDate());

        // 创建 HttpEntity 对象
        HttpEntity<OpenDoorParam> requestEntity = new HttpEntity<>(apply, headers);

        // 调用 POST 接口
        ResponseEntity<KuodaoParam> response = restTemplate.postForEntity(url,requestEntity,KuodaoParam.class);

        if(response.getBody().getResultCode()!=0){
            return null;}

        KuodaoParam returnKuodao =JSONNUtil.toEntityWithStatusCheck(response, KuodaoParam.class);

        String pwdurl = "https://api.kdware.cn/hapi/v1.1/issueGuestTimeLimitedPasswd";


        KuodaoParam applyPwd = new KuodaoParam();
        applyPwd.setSessionid(kparam.getSessionid());
        applyPwd.setOwner(kparam.getOwner());
        applyPwd.setSysID(kparam.getSysID());
        applyPwd.setRoomID(kparam.getRoomID());
        applyPwd.setEndDate(kparam.getEndDate());
        // 请求获取密钥
        HttpEntity<KuodaoParam> requestoutEntity = new HttpEntity<>(applyPwd, headers);

        // 调用 POST 接口
        ResponseEntity<KuodaoParam> pwdresponse = restTemplate.postForEntity(pwdurl,requestoutEntity,KuodaoParam.class);
        outLogin(kparam.getSessionid());

        if(pwdresponse.getBody().getResultCode()!=0){
            return null;}

        returnKuodao.setPinCode(JSONNUtil.toEntityWithStatusCheck(pwdresponse, KuodaoParam.class).getPinCode());

        return  returnKuodao;
    }

    /**
     * 密钥申请-钥匙 -撤销
     */
    public void revoke(String keyId) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        String url = "https://api.kdware.cn/hapi/v1.1/cancelGuestKeyByKeyID";
        headers.setContentType(MediaType.APPLICATION_JSON);

        Map<String,String> revoke = new HashMap<>();
        revoke.put("sessionid",getKuodaoSessionId());
        revoke.put("keyID",keyId);

        // 创建 HttpEntity 对象
        HttpEntity<Map> requestEntity = new HttpEntity<>(revoke, headers);

        // 调用 POST 接口
        ResponseEntity<KuodaoParam> response = restTemplate.postForEntity(url,requestEntity,KuodaoParam.class);

        if(response.getBody().getResultCode()!=0){
            throw new ServiceException(response.getBody().getErrorString());
        }
        outLogin(revoke.get("keyId"));
    }

    /**
     * 开门记录查询
     */
    public KuodaoParam querydoorRecord(KuodaoParam kparam) {
        kparam.setSessionid(getKuodaoSessionId());
        String url = "https://api.kdware.cn/hapi/v1.1/loadRoomEvents";

        // 请求体数据
        Map<String,Object> query =new HashMap<>();
        query.put("sessionid",kparam.getSessionid());
        if(kparam.getByRoomID()!=null)query.put("byRoomID",kparam.getRoomID());

        query.put("offset",kparam.getOffset());
        query.put("count",kparam.getCount());
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 创建 HttpEntity 对象
        HttpEntity<Map> requestEntity = new HttpEntity<>(query, headers);

        // 调用 POST 接口
        ResponseEntity<KuodaoParam> response = restTemplate.postForEntity(url, requestEntity, KuodaoParam.class);
        if(response.getBody().getResultCode()!=0){
            System.out.println("error!:"+response.getBody().getErrorString());
            return null;}
        return  JSONNUtil.toEntityWithStatusCheck(response, KuodaoParam.class);
    }
}
